package com.hr.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.hr.dao.PubinfoDao;
import com.hr.model.PubinfoModel;
/**
 * 公告DAO
 * @author fazhen.zheng
 *
 */
@Repository
public class PubinfoDaoImpl implements PubinfoDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<PubinfoModel> findAll() {
		String sql = "select id,tn_title,tn_time,user_id from pubinfo order by tn_time desc";
		List<PubinfoModel> infoList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<PubinfoModel>(PubinfoModel.class));
		return infoList;
	}

	@Override
	public void insert(PubinfoModel pubinfoModel) {
		pubinfoModel.setId(getNewId());
		String sql = "insert into pubinfo (tn_title,tn_content,tn_time,user_id) values(?,?,?,?)";
		Object[] params = new Object[]{
				//pubinfoModel.getId(),
				pubinfoModel.getTn_title(),
				pubinfoModel.getTn_content(),
				pubinfoModel.getTn_time(),
				pubinfoModel.getUser_id()
		};
		jdbcTemplate.update(sql, params);
	}
	/**
	 * 自定生成部门编号
	 * @return
	 */
	private long getNewId(){
		String code="001";
		code = jdbcTemplate.queryForObject("select max(id) from pubinfo", String.class);
		if(code==null)
			return Long.parseLong("001");
		int num = Integer.parseInt(code);
		num++;
		if(num<10)
			code="00"+num;
		else if(num<100)
			code="0"+num;
		else
			code = ""+num;
		
		return Long.parseLong(code);
	}

	@Override
	public void delete(String id) {
		String sql = "delete from  pubinfo where id=?";
		jdbcTemplate.update(sql, id);
	}
	//根据主键查询
	@Override
	public PubinfoModel findByPrimaryKey(String id) {
		String sql = "select *  from  pubinfo where id=?";
		PubinfoModel ubinfoModel = jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<PubinfoModel>(PubinfoModel.class));
		return ubinfoModel;
	}
}
